const INIT_STATE = "init";
const CHANGE_STATE = "changed";

const DefalutOps = {
  critical_point: 0,
  change() {},
  reset() {},
};

class Scroll {
  constructor(options, scollContainer, eventEl = scollContainer) {
    this.options = { ...DefalutOps, ...options };
    this.critical_point = options.critical_point;
    this.scollContainer = scollContainer;
    this.eventEl = eventEl;
    this.setState(INIT_STATE);
    this.bindEvent();
  }

  setState(state) {
    this.state = state;
  }

  bindEvent() {
    this.scollContainer.addEventListener(
      "scroll",
      () => {
        const { change, reset } = this.options;
        if (this.needToChange()) {
          if (typeof change === "function") {
            change();
            this.setState(CHANGE_STATE);
          }
        } else if (this.needToReset()) {
          if (typeof reset === "function") {
            reset();
            this.setState(INIT_STATE);
          }
        }
      },
      false
    );
  }
  //改变状态
  needToChange() {
    return (
      this.state !== CHANGE_STATE &&
      this.eventEl.scrollTop > this.critical_point
    );
  }

  //恢复初始状态
  needToReset() {
    return (
      this.state !== INIT_STATE && this.eventEl.scrollTop <= this.critical_point
    );
  }
}

export default Scroll;
